﻿using AiXiu.BLL;
using AiXiu.Common;
using AiXiu.IBLL;
using AiXiu.Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace AiXiu.WebSite
{
    /// <summary>
    /// 编辑个人资料页
    /// </summary>
    public partial class PersonalEdit : Page
    {
        private District district;
        private ListItem ddlTips = new ListItem("- 请选择 -", "");

        public PersonalEdit()
        {
            // 加载省市信息
            using (FileStream fileStream = new FileStream(Server.MapPath("~/App_Data/district.json"), FileMode.Open))
            {
                using (StreamReader streamReader = new StreamReader(fileStream, Encoding.Default))
                {
                    string distictString = streamReader.ReadToEnd();
                    district = JsonConvert.DeserializeObject<District>(distictString);
                }
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // 读取用户资料
                TBUsers user = IdentityManager.ReadUser();
                // 显示用户资料
                this.txtNickName.Text = user.NickName ?? "";
                this.ddlSex.SelectedIndex = user.Sex;
                this.txtBirthday.Text = user.Birthday.HasValue ? user.Birthday.Value.ToString("yyyy-MM-dd") : "";
                if (!string.IsNullOrWhiteSpace(user.Address))
                {
                    string[] addressArray = user.Address.Split(' ');
                    if (addressArray.Length > 0)
                    {
                        BindProvinces(addressArray[0]);
                        BindCitys(addressArray[0], addressArray[1]);
                    }
                    else
                    {
                        BindProvinces();
                    }
                }
                else
                {
                    BindProvinces();
                }
                if (!string.IsNullOrWhiteSpace(user.Hobby))
                {
                    string[] hobbyArray = user.Hobby.Split(' ');
                    for (int i = 0; i < this.cblHobby.Items.Count; i++)
                    {
                        this.cblHobby.Items[i].Selected = hobbyArray.Contains(this.cblHobby.Items[i].Value);
                    }
                }
            }
        }

        /// <summary>
        /// 更新按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnProfile_Click(object sender, EventArgs e)
        {
            // 读取信息
            TBUsers profile = IdentityManager.ReadUser();
            profile.NickName = this.txtNickName.Text;
            profile.Sex = this.ddlSex.SelectedIndex;
            if (!string.IsNullOrEmpty(this.txtBirthday.Text))
            {
                profile.Birthday = DateTime.Parse(this.txtBirthday.Text);
            }
            profile.Address = $"{this.ddlProvince.SelectedValue} {this.ddlCity.SelectedValue}";
            List<string> hobbyList = new List<string>();
            foreach (ListItem item in this.cblHobby.Items)
            {
                if (item.Selected)
                {
                    hobbyList.Add(item.Value);
                }
            }
            profile.Hobby = string.Join(" ", hobbyList);
            // 更新资料
            IUserManager userManager = new UserManager();
            OperResult<TBUsers> editResult = userManager.EditWithoutAvatar(profile);
            if (editResult.StatusCode == StatusCode.Succeed)
            {
                TBUsers userEntity = editResult.ReadResult();
                // 读取缓存用户资料
                TBUsers userCookie = IdentityManager.ReadUser();
                if (userCookie == null)
                {
                    this.Alert("cookienull", "缓存读取出错！");
                }
                // 更新用户资料
                userCookie.NickName = userEntity.NickName;
                userCookie.Sex = userEntity.Sex;
                userCookie.Birthday = userEntity.Birthday;
                userCookie.Address = userEntity.Address;
                userCookie.Hobby = userEntity.Hobby;
                // 缓存用户资料
                IdentityManager.SaveUser(userCookie);
                // 跳转到个人页
                Response.Redirect("Personal.aspx");
            }
            else
            {
                this.Alert("editerror", editResult.Message);
            }
        }

        /// <summary>
        /// 省份选项索引变更事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ddlProvince_SelectedIndexChanged(object sender, EventArgs e)
        {
            string provinceName = this.ddlProvince.SelectedValue;
            BindCitys(provinceName);
        }

        /// <summary>
        /// 绑定省份下拉列表
        /// </summary>
        /// <param name="provinceName"></param>
        private void BindProvinces(string provinceName = null)
        {
            // 绑定省份列表
            this.ddlProvince.DataSource = district.Provinces;
            this.ddlProvince.DataValueField = "ProvinceName";
            this.ddlProvince.DataTextField = "ProvinceName";
            this.ddlProvince.DataBind();
            this.ddlProvince.Items.Insert(0, ddlTips);
            // 设置省份默认选中项
            if (string.IsNullOrWhiteSpace(provinceName))
            {
                this.ddlProvince.SelectedIndex = 0;
            }
            else
            {
                this.ddlProvince.SelectedValue = provinceName;
            }
        }

        /// <summary>
        /// 绑定城市下拉列表
        /// </summary>
        /// <param name="provinceName"></param>
        /// <param name="cityName"></param>
        private void BindCitys(string provinceName, string cityName = null)
        {
            // 未选择省份名称时，清空城市列表
            if (string.IsNullOrWhiteSpace(provinceName))
            {
                this.ddlCity.Items.Clear();
                this.ddlCity.Items.Add(ddlTips);
                return;
            }
            // 未查找到省份名称时，清空城市列表
            Province province = district.Provinces.SingleOrDefault(m => m.ProvinceName == provinceName);
            if (province == null)
            {
                this.ddlCity.Items.Clear();
                this.ddlCity.Items.Add(ddlTips);
                return;
            }
            // 绑定省份下的城市列表
            this.ddlCity.DataSource = province.Citys;
            this.ddlCity.DataValueField = "CityName";
            this.ddlCity.DataTextField = "CityName";
            this.ddlCity.DataBind();
            this.ddlCity.Items.Insert(0, ddlTips);
            // 设置城市默认选中项
            if (string.IsNullOrWhiteSpace(cityName))
            {
                this.ddlCity.SelectedIndex = 0;
            }
            else
            {
                this.ddlCity.SelectedValue = cityName;
            }
        }
    }
}